home *** CD-ROM | disk | FTP | other *** search
/ Visual Basic Source Code / Visual Basic Source Code.iso / vbsource / export1a / clsmerge.cls next >
Encoding:
Visual Basic class definition  |  1999-09-30  |  12.9 KB  |  451 lines

  1. VERSION 1.0 CLASS
  2. BEGIN
  3.   MultiUse = -1  'True
  4.   Persistable = 0  'NotPersistable
  5.   DataBindingBehavior = 0  'vbNone
  6.   DataSourceBehavior  = 0  'vbNone
  7.   MTSTransactionMode  = 0  'NotAnMTSObject
  8. END
  9. Attribute VB_Name = "clsWordMerge"
  10. Attribute VB_GlobalNameSpace = False
  11. Attribute VB_Creatable = True
  12. Attribute VB_PredeclaredId = False
  13. Attribute VB_Exposed = False
  14. Option Explicit
  15.  
  16. '**(CLASS HEADER)*************************************************
  17. '*
  18. '*   Author:  Tmess  EMail: MessinaThomas@Hotmail.com
  19. '*  Purpose:  1.Create New word Document
  20. '*            2.Set the pagesetup and Add text to the document
  21. '*            3.Position and format the text
  22. '*            4.Insert data from a database into the table
  23. '*            5.Save the document
  24. '*            6.Create a new e-mail using outlook
  25. '*            7.Insert the document into an e-mail
  26. '*            8.Send the e-mail
  27. '*            9.Delete the document
  28. '*            10.All errors are logged in a textfile and can be raised in the form
  29. '*
  30. '*  You can use all the above or some
  31. '*
  32. '*  Use this at your own risk. I am not responsible for misuse of this class
  33. '*   Please improve if you want. Let me know
  34. '*
  35. '******************************************************************
  36.  
  37. Public Enum PageSetups
  38.    Landscape = wdOrientLandscape
  39.    Portrait = wdOrientPortrait
  40. End Enum
  41.  
  42. Public Enum Alignment
  43.     Center = WdParagraphAlignment.wdAlignParagraphCenter
  44.     Left = WdParagraphAlignment.wdAlignParagraphLeft
  45.     Right = WdParagraphAlignment.wdAlignParagraphRight
  46.     Justify = WdParagraphAlignment.wdAlignParagraphJustify
  47. End Enum
  48.  
  49. Private m_ProcedureName As String 'Name of current procedure: for error handling
  50. Private m_dbPathName As String 'Path and name of Database
  51. Private m_IsConnected As Boolean 'Is there a connection to database
  52. Private m_NumOfLines As Integer 'Number of blank lines to insert
  53. Private m_StrHyperlink As String 'Name of hyperlink
  54. Private m_Strsubject As String 'Subject of E-mail message
  55. Private m_StrTo As String 'Recipient address
  56. Private m_StrToAdd As String 'Text to add to Word doc
  57. Private m_VarMsgBody As Variant 'Body of e-mail message
  58. Private m_FontSize As Integer 'Font size of StrToAdd
  59. Private m_FontBold As Boolean 'Is strToAdd bold or Not
  60. Private m_ParaAlign As Integer 'StrToAdd alignment SEE ENUM ALIGNMENT
  61. Private m_PageSetup As Integer 'Page setup of Word Doc SEE ENUM PAGESETUPS
  62. Private m_Database As Dao.Database 'DAO database object
  63. Private m_Recordset As Dao.Recordset 'DAO Recordset object
  64. Private m_sql As String 'SQL String passed from client
  65. Private i As Integer 'Used in for next loop
  66.  
  67. Private wrdApp As Word.Application 'MS Word object
  68. Private wrdDoc As Word.Document 'MS Word Document
  69. Private wrdSelection As Word.Selection 'MS Word Selection
  70. Private strDocName As String 'MS Word document name
  71.  
  72. 'Raised if merge successful
  73. Public Event MergeComplete()
  74. 'Raised if merge Unsuccessful
  75. Public Event MergeFailed(errNum As Integer, msgWhy As String)
  76. 'Raised if merge document saved successfully
  77. Public Event DocumentSaved()
  78. 'Raised if merge document saved Unsuccessfully
  79. Public Event DocumentNotSaved(errNum As Integer, msgWhy As String)
  80. 'Raised if document was e-mailed successfully
  81. Public Event MessageSent()
  82. 'Raised if document was e-mailed Unsuccessfully
  83. Public Event MessageNotSent(errNum As Integer, msgWhy As String)
  84. 'Raised if database connection was successful
  85. Public Event ConnectionSuccessful()
  86. 'Raised if database connection was Unsuccessful
  87. Public Event ConnectionNotSuccessful(errNum As Integer, msgWhy As String)
  88. 'Raise for unknown errors
  89. Public Event UnknownError(errNum As Integer, msgWhy As String)
  90.  
  91. Private Sub Class_Initialize()
  92.  
  93.     Set wrdApp = New Word.Application
  94.     
  95.     'Set to false if you don't want to see the word doc
  96.     wrdApp.Visible = True
  97.     'Database connection has not been established yet
  98.     m_IsConnected = False
  99. End Sub
  100.  
  101.  
  102. Private Sub Class_Terminate()
  103.  
  104.     wrdApp.Quit
  105.     Set wrdSelection = Nothing
  106.     Set wrdDoc = Nothing
  107.     Set wrdApp = Nothing
  108.  
  109. End Sub
  110. Public Sub OpenNewDoc()
  111.  
  112.     Set wrdDoc = wrdApp.Documents.Add
  113.     wrdDoc.Select
  114.     
  115.     Set wrdSelection = wrdApp.Selection
  116.     
  117. End Sub
  118.  
  119. Public Property Let PageSetupDocument(IntPageSetup As Integer)
  120.  
  121.     m_PageSetup = IntPageSetup
  122.     wrdDoc.PageSetup.Orientation = m_PageSetup
  123.     
  124. End Property
  125.  
  126. Public Sub DatabaseToConnect(dbPathAndName As String)
  127. On Error GoTo Err_Handler
  128.  
  129.     'Check to see if a connection to a database is already opened
  130.     If m_IsConnected Then
  131.         MsgBox "Connection already established. Close the current " & _
  132.          "connection first before opening a new database", vbInformation, _
  133.          "Connection Already Established"
  134.         Exit Sub
  135.     End If
  136.     
  137.     m_dbPathName = dbPathAndName
  138.     
  139.     'Check to see if the path and the database exists
  140.     If FileExist(m_dbPathName) = False Then
  141.      MsgBox "File Not Found. Could not Establish Connection", vbCritical, _
  142.             "File Not Found"
  143.         Exit Sub
  144.     End If
  145.     
  146.     Set m_Database = DBEngine.OpenDatabase(m_dbPathName)
  147.     m_IsConnected = True
  148.     
  149. Exit Sub
  150.     
  151. Err_Handler:
  152.         m_ProcedureName = "DatabaseToConnect"
  153.         Call ClsErrorHandler
  154.         
  155. End Sub
  156. Public Sub DatabaseDisConnect()
  157.     'Close and Release database object from memory
  158.     If m_IsConnected Then
  159.         m_Database.Close
  160.         Set m_Database = Nothing
  161.         m_IsConnected = False
  162.         Exit Sub
  163.     End If
  164.     
  165. End Sub
  166.  
  167. Public Property Let InsertLinesInDoc(numOfLines As Integer)
  168.  
  169.     m_NumOfLines = numOfLines
  170.     InsertLines m_NumOfLines
  171.     
  172. End Property
  173.  
  174. Public Sub InsertText(strToAdd As String, IntFontSize As Integer, _
  175.     blBold As Boolean, intParagraphAlign As Integer)
  176.  
  177.     m_StrToAdd = strToAdd
  178.     m_FontBold = blBold
  179.     m_FontSize = IntFontSize
  180.     m_ParaAlign = intParagraphAlign
  181.     
  182.     InsertTextIntoDoc
  183.     
  184. End Sub
  185.  
  186. Public Property Let InsertHyperlinkAddress(strHyperlink As String)
  187.  
  188.     m_StrHyperlink = strHyperlink
  189.     InsertHyperlink
  190.     
  191. End Property
  192.  
  193. Public Sub InsertTableWithData(strRecordSet As String, _
  194.         Optional RecordSetToUse As Dao.Recordset)
  195. On Error GoTo Error_Handler
  196.         
  197.  Dim intNumofRows As Integer
  198.  Dim intNumofColumns As Integer
  199.  Dim p As Integer, ColWidth As Integer
  200.  
  201.     'Check to see if a new connection to the database
  202.      'has been established
  203.     If m_IsConnected Then
  204.         m_sql = strRecordSet
  205.         Set m_Recordset = m_Database.OpenRecordset(m_sql)
  206.     Else
  207.         Set m_Recordset = RecordSetToUse
  208.     End If
  209.  
  210.     m_Recordset.MoveLast
  211.     m_Recordset.MoveFirst
  212.  
  213.     intNumofColumns = m_Recordset.Fields.Count
  214.     intNumofRows = m_Recordset.RecordCount
  215.  
  216.     'Insert a new table with rows according to recordCount plus Column header
  217.     'and the number of columns in the recordset
  218.      
  219.     wrdDoc.Tables.Add wrdSelection.Range, NumRows:=intNumofRows + 1, _
  220.     NumColumns:=intNumofColumns
  221.     
  222.     With wrdDoc.Tables(1)
  223.     ' Set the column widths
  224.      For i = 0 To intNumofColumns - 1
  225.      ColWidth = Len(m_Recordset.Fields(i).Name)
  226.         .Columns(i + 1).SetWidth ColWidth * 25, wdAdjustNone
  227.         .Cell(1, i + 1).Range.InsertAfter UCase(m_Recordset.Fields(i).Name)
  228.      Next i
  229.         
  230.         ' Set the shading on the first row to light gray
  231.         .Rows(1).Cells.Shading.BackgroundPatternColorIndex = wdGray25
  232.         
  233.         ' Bold the first row
  234.         .Rows(1).Range.Bold = True
  235.         
  236.         ' Center the text in Cell (1,1)
  237.         .Cell(1, 1).Range.Paragraphs.Alignment = wdAlignParagraphCenter
  238.         
  239.         ' Fill each row of the table with data
  240.         For i = 1 To intNumofRows
  241.          For p = 1 To intNumofColumns
  242.           FillRow i + 1, p, m_Recordset.Fields(p - 1)
  243.          Next p
  244.          p = 1
  245.          m_Recordset.MoveNext
  246.         Next i
  247.     End With
  248.     
  249.     RaiseEvent MergeComplete
  250.     
  251. Exit_Handler:
  252.  
  253.    'release objects from memory
  254.    If m_IsConnected Then
  255.     m_Recordset.Close
  256.    End If
  257.    
  258.    Set m_Recordset = Nothing
  259.   Exit Sub
  260.     
  261. Error_Handler:
  262.     m_ProcedureName = "InsertTableWithData"
  263.     Call ClsErrorHandler
  264.     Resume Exit_Handler
  265.         
  266. End Sub
  267. Private Sub InsertHyperlink()
  268.     'Inserts a hyperlink
  269.  
  270.     wrdSelection.Hyperlinks.Add Anchor:=wrdSelection.Range, _
  271.     Address:=m_StrHyperlink
  272.     
  273. End Sub
  274.  
  275. Private Sub InsertTextIntoDoc()
  276.     'This routines insert text into the word document and sets the font
  277.     'and alignment
  278.  
  279.     wrdSelection.ParagraphFormat.Alignment = m_ParaAlign
  280.     wrdSelection.Font.Size = m_FontSize
  281.     wrdSelection.Font.Bold = m_FontBold
  282.     wrdSelection.TypeText m_StrToAdd
  283.     
  284. End Sub
  285. Private Sub InsertLines(LineNum As Integer)
  286.     Dim iCount As Integer
  287.     'Insert blank lines in Word document
  288.     For iCount = 1 To LineNum
  289.         wrdApp.Selection.TypeParagraph
  290.     Next iCount
  291. End Sub
  292.    
  293. Private Sub FillRow(Row As Integer, Column, _
  294.                    Text1 As String)
  295. ' Insert the data into the specific cell
  296.                    
  297.     With wrdDoc.Tables(1)
  298.         .Cell(Row, Column).Range.InsertAfter Text1
  299.     End With
  300.     
  301. End Sub
  302. Public Sub printDoc()
  303.     'print out the word doc
  304.     wrdDoc.PrintOut
  305.     
  306. End Sub
  307. Public Sub SendDoc(ByVal strTo As String, ByVal strSubject As String, _
  308.     varMsgBody As Variant)
  309.  
  310. On Error GoTo OutLookTrap
  311.     'Mail the word document to recipient specified
  312.  
  313. Dim ObjOutlook As Outlook.Application
  314. Dim ObjMailItem As Outlook.MailItem
  315.  
  316.         
  317.     m_Strsubject = strSubject
  318.     m_StrTo = strTo
  319.     m_VarMsgBody = varMsgBody
  320.  
  321.     'Check to see if the e-mail address is correct by checking the format
  322.     If checkEmailAddress = False Then
  323.      m_ProcedureName = "SendDoc"
  324.      Call ClsErrorHandler
  325.      Exit Sub
  326.     End If
  327.     
  328.         Set ObjOutlook = New Outlook.Application
  329.         Set ObjMailItem = ObjOutlook.CreateItem(olMailItem)
  330.         
  331.     'create e-mail and insert attachment
  332.         With ObjMailItem
  333.             .Recipients.Add m_StrTo
  334.             .Subject = m_Strsubject
  335.             .Body = m_VarMsgBody & vbCrLf & vbCrLf
  336.             .Attachments.Add strDocName
  337.         End With
  338.         
  339.         ObjMailItem.Send
  340.         RaiseEvent MessageSent
  341.         
  342. OutLookTrapExit:
  343.         Set ObjMailItem = Nothing
  344.         Set ObjOutlook = Nothing
  345.         Exit Sub
  346. OutLookTrap:
  347.         m_ProcedureName = "SendDoc"
  348.         Resume OutLookTrapExit
  349. End Sub
  350. Public Sub SaveDocAsAndClose(Path As String, StrToSaveAs As String)
  351. On Error GoTo Err_Handler
  352.     'Check to see if the path exists
  353.     If DriveExist(Path) = False Then Exit Sub
  354.     
  355.     ' Save the document, close it
  356.     strDocName = Path & StrToSaveAs & ".doc"
  357.     wrdDoc.SaveAs strDocName
  358.     wrdDoc.Close
  359.     
  360.     RaiseEvent DocumentSaved
  361.     
  362. Exit_Err_Handler:
  363.    Exit Sub
  364.     
  365. Err_Handler:
  366.     m_ProcedureName = "SaveDocAsAndClose"
  367.     Resume Exit_Err_Handler
  368.     
  369. End Sub
  370.  
  371. Public Sub DeleteDoc(PathAndDocName As String)
  372.    'Delete a file
  373.    If FileExist(PathAndDocName) Then
  374.     Kill PathAndDocName
  375.    End If
  376.        
  377. End Sub
  378. Public Sub InsertCurrentDate()
  379.     'Inserts the current date with the deafult font
  380.  
  381.     wrdSelection.InsertDateTime _
  382.     DateTimeFormat:="dddd, MMMM dd, yyyy", InsertAsField:=False
  383.     
  384. End Sub
  385.  
  386. Private Function checkEmailAddress() As Boolean
  387. On Error Resume Next
  388.     'parses e-mail address to see if is correct
  389.     i = InStr(m_StrTo, "@")
  390.     checkEmailAddress = (InStr(i + 1, m_StrTo, ".") > 0)
  391.    
  392. End Function
  393.  
  394. Private Function FileExist(filename As String) As Boolean
  395. On Error Resume Next
  396.  
  397.     FileExist = (Dir$(UCase((filename))) <> "")
  398.  
  399. End Function
  400.  
  401. Private Function DriveExist(Path As String) As Boolean
  402. On Error Resume Next
  403.  
  404.     DriveExist = (Dir(UCase((Path))) <> "")
  405.  
  406. End Function
  407.  
  408. Private Sub ClsErrorHandler()
  409.     'Generic Error handling routine
  410.  
  411. Dim handleErr As String
  412. Dim textfile As String
  413.  
  414.     'Raise the event according the procedure passed. Will write all errors
  415.      'to an error log. Errors on the form will only be visible if
  416.      'the event is active and a debug.print statement or message box
  417.      'is inserted
  418.     
  419. Select Case m_ProcedureName
  420.  
  421.     Case Is = "SaveDocAsAndClose"
  422.         RaiseEvent DocumentNotSaved(Err.Number, Err.Description)
  423.         
  424.     Case Is = "SendDoc"
  425.         RaiseEvent MessageNotSent(Err.Number, Err.Description)
  426.         
  427.     Case Is = "InsertTableWithData"
  428.         RaiseEvent MergeFailed(Err.Number, Err.Description)
  429.         
  430.     Case Is = "DatabaseToConnect"
  431.         RaiseEvent ConnectionNotSuccessful(Err.Number, Err.Description)
  432.         
  433.     Case Else
  434.         RaiseEvent UnknownError(Err.Number, Err.Description)
  435.         
  436. End Select
  437.  
  438.     'Log the errors to an error log
  439.     textfile = App.Path & "\ErrogLog.txt"
  440.     handleErr = "Error: " & Err.Number & " " & Err.Description & _
  441.                  " " & Err.Source
  442.  
  443.     Open textfile For Append As #1 'write error to textfile
  444.         Write #1, Now; handleErr; m_ProcedureName
  445.     Close #1
  446.  
  447.     Err.Clear
  448.  
  449. End Sub
  450.  
  451.